// import { start as s1 } from './run';
// import { start as s2 } from './ruler';
// import { start as s3 } from './start';
import './index.less';
import { Toolsbar } from '../tools-bar';
import { ZExcel } from '../index';
import { DataHandlePlugin } from '../pugins/data-handle.plugin';

import { 
    data1, 
    data2, 
    getMoreData, 
    userData, 
    createHeader, 
    selectColorData, 
    MutipleSelectData,
    linkDate,
    fileData,
    relationData
} from './mock/table-data'
// window.onload = function() {
//     return;
//     s1();
//     s2();
//     s3();
// }
const content = `
<div class="z-table-example">
    <div class="z-header">
        <div class="z-logo">
            <img src="/favicon.ico"/>
        </div>
        <div class="z-pagename">
            <div>
            Z-
            </div>
            <div>
                EXCEL
            </div>
        </div>
        <div class="z-links" style="display: none;">

        </div>
        <div class="z-render-info">
            <div class="z-item z-table-setting-time" style="display:none;"><span>表单设计:</span><span class="value">0ms</span></div>
            <div class="z-item z-table-data-time" style="display:none;"><span>表单数据:</span><span class="value">0ms</span></div>
            <div class="z-item z-table-handle-time" style="display:none;"><span>数据处理:</span><span class="value">0ms</span></div>
            <div class="z-item z-table-render-time"><span>渲染:</span><span class="value">0ms</span></div>
            <div class="z-open-setting" style="cursor:pointer"><a>打开配置</a></div>
        </div>
    </div>
    <div class="z-content">
        <div class="z-table-tools-container"></div>
        <div class="z-table-container"></div>
    </div>
    <div class="dev-modal">
        <div class="modal-title">获取数据</div>
        <div class="modal-content">
            <div class="z-input z-cookie">
                cookie：<input />
            </div>
            <div class="z-input z-form-id">
                表单ID：<input />
            </div>
        </div>
        <div class="modal-operate">
            <button class="z-btn z-cancel">取消</button>
            <button class="z-btn z-sure">确定</button>
        </div>
    </div>
</div>
`;
(() => {
    // return
    let body = document.querySelector('body');
    body.innerHTML = content;
    let toolsContainer = document.querySelector('.z-table-tools-container') as HTMLElement;
    let tableContainer = document.querySelector('.z-table-container') as HTMLElement;

    let intance = ZExcel.create(tableContainer);
    let toolContentInstance = new Toolsbar(toolsContainer, intance);
    console.log(intance.activeTable)
    fetch('/assets/form-1612.json')
    const  dataHandle: DataHandlePlugin = intance.activeTable.pluginManager.getPlugin('DataHandlePlugin');

        // @ts-ignore
        dataHandle.setData(data1);
        // @ts-ignore
        // dataHandle.setData(data2);
        // dataHandle.setData(getMoreData(1000, 500));
        // dataHandle.setData(userData);
        // dataHandle.setData(createHeader());
        // dataHandle.setData(selectColorData);
        // dataHandle.setData(MutipleSelectData);
        // dataHandle.setData(linkDate);
        // dataHandle.setData(fileData)
        // dataHandle.setData(relationData);
    // intance.activeTable.pluginManager.getPlugin('')
    
    // document.querySelector('.z-open-setting').addEventListener('click', () => {
    //     (document.querySelector('.dev-modal') as HTMLElement).style.display = 'flex';
    //     // (document.querySelector('.dev-modal .z-url input') as HTMLInputElement).value = localStorage.getItem('url');
    //     (document.querySelector('.dev-modal .z-cookie input') as HTMLInputElement).value = localStorage.getItem('cookie');
    //     (document.querySelector('.dev-modal .z-form-id input') as HTMLInputElement).value = localStorage.getItem('formId');
    // });
    // document.querySelector('.dev-modal .z-cancel').addEventListener('click', () => {
    //     (document.querySelector('.dev-modal') as HTMLElement).style.display = 'none';
    // });
    // document.querySelector('.dev-modal .z-sure').addEventListener('click', () => {
    //     // localStorage.setItem('url', (document.querySelector('.dev-modal .z-url input') as HTMLInputElement).value);
    //     localStorage.setItem('cookie', (document.querySelector('.dev-modal .z-cookie input') as HTMLInputElement).value);
    //     localStorage.setItem('formId', (document.querySelector('.dev-modal .z-form-id input') as HTMLInputElement).value);
    //     (document.querySelector('.dev-modal') as HTMLElement).style.display = 'none';
    // });
    return;
    Promise.all([
        // fetch(`assets/form-1612.json?time=${__BUILD_TIME__}`).then(res => res.json()),
        // fetch(`assets/1612-data.json?time=${__BUILD_TIME__}`).then(res => res.json())
        fetch(`assets/8009-setting.json?time=${__BUILD_TIME__}`).then(res => res.json()),
        fetch(`assets/8009-data.json?time=${__BUILD_TIME__}`).then(res => res.json())
    ]).then(([_setting, _data]) => {
        const setting = _setting.data.setting;
        const fields = setting.fields;
        const datas = _data.data.list.map((item: any) => Object.assign(item.form_datas, {fid: item.id}));
        console.log(fields);
        console.log(datas);
        const tableData: any = {
            mergeCells: [],
            colConf: [],
            fullCtrl: [],
            datas: [],
            config: {
                freeze: {row: 4, col: 3}
            }
        }
        let headers: {row: number, cells: any[]} = {row: 0, cells: []};
        const headerMap: Map<string, {id: string,col: number, controlType: string, group_id: string}> = new Map();
        const colToFidMap: Map<number, string> = new Map();
        const controlTypes: Set<string> = new Set();
        for(let i = 0; i < fields.length; i++) {
            let field = fields[i];
            controlTypes.add(field.controlType)
            field.col = i;
            headerMap.set(field.id, field);
            colToFidMap.set(i, field.id);
            if(field.layout && field.layout.width) {
                tableData.colConf.push({
                    col: i,
                    width: field.layout.width
                })
            }
            headers.cells.push({
                col: i,
                fill: {background: {color: '#F7F8FF'}},
                type: 'header',
                value: {
                    type: (() => {
                        if(field.group_id) {
                            return 'ref';
                        } else {
                            return field.controlType
                        }
                    })(),
                    name: field.label
                }
            });
        }   
        tableData.datas.push(headers);
        for(let i = 0; i < datas.length; i++) {
            let row: {row: number, cells: any[]} = {row: i + 1, cells: []};
            let data = datas[i];
            for(let fid in data) {
                let value = data[fid];
                if(value === null || value === '' || (Array.isArray(value) && value.length === 0)) {
                    continue;
                }
                let field = headerMap.get(fid);
                if(!field) {
                    continue;
                }
                if(field.group_id) {
                    if(field.controlType === 'text') {
                        row.cells.push({
                            col: field.col,
                            type: 'ref',
                            value: {
                                type: 'kpd-text',
                                list: data[fid].map((item: any) => item.value)
                            }
                        })
                    }
                    if(field.controlType === 'telephone') {
                        row.cells.push({
                            col: field.col,
                            type: 'ref',
                            value: {
                                type: 'kpd-text',
                                list: data[fid].map((item: any) => item.value).filter((item: any) => item != null)
                            }
                        })
                    }
                    if(field.controlType === 'file') {
                        // console.log(data[fid])
                        let files: {name: string, type: string}[] = [];
                        for(let group of data[fid]) {
                            if(!Array.isArray(group.value)) continue;
                            for(let file of group.value) {
                                files.push(file)
                            }
                        }
                        row.cells.push({
                            col: field.col,
                            type: 'ref',
                            value: {
                                type: 'file',
                                list: files
                            }
                        })
                    }
                    if(field.controlType === 'member') {
                        console.log(data[fid])
                    }
                    if(field.controlType === 'textarea') {
                        console.log(data[fid])
                    }
                } else {
                    if(field.controlType === 'number'  || field.controlType === 'autonumber') {
                        row.cells.push({
                            col: field.col,
                            type: 'kpd-text',
                            value: {
                                value: data[fid].toString()
                            }
                        })
                    }
                    if(field.controlType === 'text') {
                        row.cells.push({
                            col: field.col,
                            type: 'kpd-text',
                            value: {
                                value: data[fid].toString()
                            }
                        })
                    }
                    if(field.controlType === 'member') {
                        row.cells.push({
                            col: field.col,
                            type: 'users',
                            value: data[fid]
                        })
                    }
                    if(field.controlType === 'select_color') {
                        if(isNaN(Number(data[fid]))) {
                            row.cells.push({
                                col: field.col,
                                type: 'kpd-text',
                                value: {
                                    value: data[fid].toString()
                                }
                            })
                        } else {
                            // @ts-ignore
                            let find = field.options.find((item: any) => item.value == data[fid]);
                            if(find) {
                                row.cells.push({
                                    col: field.col,
                                    type: 'select-color',
                                    value: {
                                        text: find.label,
                                        color: find.color ? find.color : '#4e4e4e' 
                                    }
                                })
                            }
  
                        }
                    }
                    if(field.controlType === 'multiple_select') {
                        row.cells.push({
                            col: field.col,
                            type: 'select-color',
                            // @ts-ignore
                            value: data[fid].map((value: any) => {
                                // @ts-ignore
                                let otpion = field.options.find((item: any) => item.value == value);
                                if(!otpion) {
                                    return null
                                }
                                return {
                                    text: otpion.label
                                }
                            }).filter((val: any) => val !== null)
                        })
                    }
                    if(field.controlType === 'date') {
                        row.cells.push({
                            col: field.col,
                            type: 'kpd-text',
                            value: {
                                value: data[fid].toString()
                            }
                        })
                    }
                    if(field.controlType === 'telephone') {
                        row.cells.push({
                            col: field.col,
                            type: 'text',
                            value: {
                                value: data[fid]
                            }
                        })
                    }
                    if(field.controlType === 'textarea') {
                        row.cells.push({
                            col: field.col,
                            type: 'kpd-text',
                            value: {
                                value: data[fid]
                            }
                        })
                    }
                    if(field.controlType === 'file') {
                        // @ts-ignore
                        row.cells.push({
                            col: field.col,
                            type: 'file',
                            value: data[fid]
                        })
                    }
                }

            }
            tableData.datas.push(row);
        }
        setTimeout(() => {
            dataHandle.setData(tableData);
        },300)
        
        console.log(tableData)
    });
    // fetch('/assets/1612-data.json').then(res => res.json()).then(res => {
    //     console.log(res);
    // })
    // fetch('/assets/form-1612.json').then(res => res.json()).then((res: any) => {
    //     const fileData: any = {
    //         mergeCells: [],
    //         colConf: [
    //             {
    //                 col: 1,
    //                 width: 100
    //             }
    //         ],
    //         fullCtrl: [],
    //         datas: [
   
    //         ]
    //     }
    //     console.log(res);
    //     let fields = res.data.setting.fields;
    //     let header: any = {
    //         row: 0,
    //         cells: [

    //         ]
    //     };
    //     // col: col,
    //     // fill: {background: {color: '#F7F8FF'}},
    //     // type: 'header',
    //     // value: {
    //     //     type: type,
    //     //     name: name
    //     // }
    //     let temp: any = {};
    //     for(let i = 0; i < fields.length; i++) {
    //         let field = fields[i];
    //         temp[field.id] = `${field.controlType} && ${field.group_id}`
    //         if(field.layout && field.layout.width) {
    //             fileData.colConf.push({
    //                 col: i,
    //                 width: field.layout.width
    //             })
    //         }
    //         header.cells.push({
    //             col: i,
    //             fill: {background: {color: '#F7F8FF'}},
    //             type: 'header',
    //             value: {
    //                 type: (() => {
    //                     if(field.group_id) {
    //                         return 'ref';
    //                     } else {
    //                         return field.controlType
    //                     }
    //                 })(),
    //                 name: field.label
    //             }
    //         });
    //     }
    //     console.log(temp)
    //     fileData.datas.push(header);
    //     dataHandle.setData(fileData)
    // });
    
})()
